package com.situ.mall.test;

import org.junit.Test;

public class Search {

	public static void main(String[] args) {
		int[] array = new int[] { 8, 17, 19, 37, 40, 73, 79, 82, 87, 95, 97, 98 };
		int target = 96;
		// 找到了返回索引位置，找不到返回-1
		int index = binarySearch(array, target);
		System.out.println(index);
	}

	private static int binarySearch(int[] array, int target) {
//		if (array == null || array.length == 0) {
//			return -1;
//		}
		int low = 0;
		int high = array.length - 1;

		int mid = (low + high) / 2;
		while (low <= high) {
			if (target == array[mid]) {
				return mid;
			}

			if (target > array[mid]) {
				low = mid + 1;
			} else if (target < array[mid]) {
				high = mid - 1;
			}
			mid = (low + high) / 2;
		}

		return -1;
	}

	@Test
	public void testBinartSearch() {
		int[] array = new int[] { 8, 17, 19, 37, 40, 73, 79, 82, 87, 95, 97, 98 };
		int target = 95;
		int low = 0;
		int high = array.length - 1;
		// 找到了返回索引位置，找不到返回-1
		int index = binarySearch2(array, target, low, high);
		System.out.println(index);
	}

	private int binarySearch2(int[] array, int target, int low, int high) {
		System.out.println("low: " + low);
		System.out.println("high: " + high);
		// 递归退出的条件
		if (low > high) {
			return -1;
		}

		int mid = (low + high) / 2;
		if (target > array[mid]) {
			return binarySearch2(array, target, mid + 1, high);
		} else if (target < array[mid]) {
			return binarySearch2(array, target, low, mid - 1);
		} else /* if (target == array[mid]) */ {
			return mid;
		}
	}

	@Test
	public void test1() {
		System.out.println(23/10*10);
	}
}
